package com.ufind.common.filter;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;

public class SecurityFilter implements Filter {

    private static Log log = LogFactory.getLog(SecurityFilter.class);

    public void init(FilterConfig config) throws ServletException {
//		ApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(config.getServletContext());   
//		utilService = (UtilService) applicationContext.getBean("utilService"); 
        log.info("******************* SecurityFilter init;");
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        String requestPath = getRequestUrl(httpRequest);
        log.info("******************* SecurityFilter doFilter;");
        log.info("******************* SecurityFilter httpRequest.getContextPath() = " + httpRequest.getContextPath());
        log.info("******************* SecurityFilter httpRequest.getRequestURI() = " + httpRequest.getRequestURI());
        log.info("******************* SecurityFilter requestPath = " + requestPath);

        if (!isProtect(requestPath)) {
            chain.doFilter(request, response);
            return;
        } else {
            HttpSession session = httpRequest.getSession(false);
            if (session == null || session.getAttribute("LOGIN_USER") == null) {
                httpResponse.sendRedirect(httpRequest.getContextPath() + "/index/login.html");
            } else {
                // 校验用户权限
                chain.doFilter(request, response);
            }
            return;
        }
    }

    public void destroy() {
        log.info("******************* SecurityFilter destroy;");
    }

    private void sendErrorMsg(HttpServletResponse httpResponse, String requestPath) {
        if (requestPath.endsWith(".do")) {
            responseJsonMsg(httpResponse);
        } else {
            responseHtmlMsg(httpResponse);
        }
    }

    private void responseJsonMsg(HttpServletResponse response) {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter out = null;
        try {
            out = response.getWriter();
            out.append("{\"msg\":\"您没有权限访问该资源，如有疑问请联系管理员！\",\"state\":\"failure\"}");
            out.flush();
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }

    private void responseHtmlMsg(HttpServletResponse response) {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=utf-8");
        OutputStream out = null;
        try {
            out = response.getOutputStream();
            out.write("您没有权限访问该资源，如有疑问请联系管理员！".getBytes("utf-8"));
            out.flush();
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    log.error(e.getMessage(), e);
                }
            }
        }
    }

    private String getRequestUrl(HttpServletRequest httpRequest) {
        String requestUrl = "";
        if ("/".equals(httpRequest.getContextPath())) {
            requestUrl = httpRequest.getRequestURI();
        } else {
            requestUrl = httpRequest.getRequestURI().substring(httpRequest.getContextPath().length());
        }
        return requestUrl;
    }

    private boolean isProtect(String requestPath) {
        if ("/index/login.html".equals(requestPath)) {
            return false;
        } else if ("/user/login.do".equals(requestPath)) {
            return false;
        } else if (requestPath.startsWith("/index/")) {
            return false;
        } else {
            return true;
        }
    }
}
